<template>
  <div class="z-upload">
    <div class="mask" :style="{ 'padding-bottom': paddingbot}">
      <input id="uploadfile" class="upload-item" type="file" multiple accept="image/*" @change="addfile" :disabled="img!=''&&showtype=='oneself'||isapp">
      <div class="upload-item" v-tap="{method:addfile}" v-if="(img==''||showtype!='oneself')&&isapp"></div>
      <img class="upload-item" :src="img" v-if="img!=''&&showtype=='oneself'" :preview="preview" ref="myimg"/>
    </div>
    <span class="mui-badge z-badge" v-if="img!=''&&showtype=='oneself'" @click="delfile">X</span>
  </div>
</template>

<script>
  export default {
    data(){
      return {
        path:'',
        imgs:[],
        files:[],
        isapp:false,
      }
    },
    props: {
      paddingbot:{
        type:String,
        default: '62.5%'
      },
      amount:{
        type:Number,
        default: 1
      },
      showtype:{
        type:String,
        default: 'oneself'
      },
      imgname:{
        type:String,
        default: 'imgname'
      },
      preview:{
        type:String,
        default: '0'
      },
      filter:{
        type:String,
        default: 'image'
      },
      img:{
        type:String,
        default: ''
      },
      uploadUrl:{
        type:String,
        default: ''
      },
      deleteUrl:{
        type:String,
        default: ''
      },
      repeatable:{
        type:Boolean,
        default: false
      }
    },
    created(){
      var that = this;
      mui.plusReady(function(){
        that.isapp=true;
      });
      that.$emit("getfile",that.imgname,that.imgs,that.files,that.img);
    },
    methods:{
      addfile(event){
        var that = this,amount=that.amount;
        if(that.repeatable){
          that.path='';
          that.imgs.splice(that.imgs.length-1,1);
          that.files.splice(that.files.length-1,1);
        }
        if(that.isapp){
          if(that.imgs.length>=amount){
            mui.alert('最多可上传'+ amount +'张!您已上传'+that.imgs.length+'张');
            return false;
          }
          mui.plusReady(function() {
            plus.nativeUI.actionSheet(
              {
                cancel:"取消",
                buttons:[
                  {title:"拍照"},
                  {title:"从相册中选择"}
                ]
              },
              function(e){//1 是拍照  2 从相册中选择
                switch(e.index){
                  case 1:that.appendByCamera();break;
                  case 2:that.appendByGallery();break;
                }
              }
            );
          });
        }else{
          try{
            let inputDOM = event.srcElement;
            var files = inputDOM.files;
            let oldLen=that.imgs.length;
            let len=files.length+oldLen;
            if(len>amount){
              mui.alert('最多可上传'+ amount +'张，您还可以上传'+(amount-oldLen)+'张');
              return false;
            }
            for (let i=0; i < files.length; i++) {
              /*判断图片大小
              let size = Math.floor(that.files[i].size / 1024);
              if (size > 5*1024*1024) {
                alert('请选择5M以内的图片！');
                return false
              }
              that.$set(that.imgs,that.files[i].name+'?'+new Date().getTime()+i,that.files[i]);
              */
              that.path=that.getObjectURL(files[i]);
              that.files=that.files.concat(files[i]);
              that.imgs=that.imgs.concat(that.path);
            }
            if(that.uploadUrl==''){
              that.$previewRefresh();
              that.$emit("getfile",that.imgname,that.imgs,that.files,that.path);
            }else{
              that.getBlobImage(that.files[that.files.length-1]);
              //that.uploadimgs(that.imgs[that.imgs.length-1],that.files[that.files.length-1]);
            }
          }catch(e){
            return false;
          }
        }
      },
      getObjectURL(file) {
        var url = null ;
        if (window.createObjectURL!=undefined) { // basic
          url = window.createObjectURL(file) ;
        } else if (window.URL!=undefined) { // mozilla(firefox)
          url = window.URL.createObjectURL(file) ;
        } else if (window.webkitURL!=undefined) { // webkit or chrome
          url = window.webkitURL.createObjectURL(file) ;
        }
        return url;
      },
      delfile(){
        var that = this;
        if(that.deleteUrl==''){
          var file = mui('#uploadfile')[0];
          file.value = '';
          that.path='';
          that.imgs.splice(that.imgs.length-1,1);
          that.files.splice(that.files.length-1,1);
          that.$emit("getfile",that.imgname,that.imgs,that.files,that.path);
        }else{
          mui.showLoading("删除中...","div");
          that.$http({url: that.deleteUrl,method:'post',params:that.$http.adornParams({'url':that.img})})
            .then(function(res){
              mui.hideLoading();
              if(res.errno==0){
                var file = mui('#uploadfile')[0];
                file.value = '';
                that.path='';
                that.imgs.splice(that.imgs.length-1,1);
                that.files.splice(that.files.length-1,1);
                that.$emit("getfile",that.imgname,that.imgs,that.files,that.path);
              }else{
                mui.toast("删除失败请重试");
              }
            })
            .catch(function (err) {
              mui.hideLoading();
              mui.toast("删除失败请重试");
            })
        }
      },
      appendByCamera(){
        var that = this;
        plus.camera.getCamera().captureImage(function(e){

          plus.io.resolveLocalFileSystemURL(e, function(entry) {
            var path = entry.toLocalURL();
            that.showImg(path);
          }, function(e) {
            mui.toast("读取拍照文件错误：" + e.message);
          });
        });
      },
      appendByGallery(){
        var that = this;
        var maxnum=that.amount-that.imgs.length;
        plus.gallery.pick(function(e){
          for (var i in e.files) {
            that.showImg(e.files[i]);
          }
        },function (e) {
          mui.toast("取消选择图片")
        },{
          filter:that.filter,
          multiple:true,
          maximum:maxnum,
          system:false,
          onmaxed:function () {
            mui.toast("本次最多可选"+maxnum+"个")
          }
        });
      },
      showImg(url){
        var that = this;
        that.files = that.files.concat(url);
        that.path = url;
        that.imgs = that.imgs.concat(url);
        if(that.uploadUrl==''){
          that.$previewRefresh();
          that.$emit("getfile",that.imgname,that.imgs,that.files,that.path);
        }else{
          that.uploadimgs(that.imgs[that.imgs.length-1],that.files[that.files.length-1]);
        }
      },
      getBlobImage(file){
        var that = this;
        var reader = new FileReader();
        var img = new Image;
        // 缩放图片需要的canvas
        var canvas = document.createElement('canvas');
        var drawer = canvas.getContext('2d');
        reader.readAsDataURL(file);
        reader.onload = function (e) {
          img.src = e.target.result;
          img.onload = function () {
            // 图片原始尺寸
            var originWidth = this.width;
            var originHeight = this.height;
            // 最大尺寸限制
            var maxWidth = 400, maxHeight = 400;
            // 目标尺寸
            var targetWidth = originWidth, targetHeight = originHeight;
            // 图片尺寸超过400x400的限制
            if (originWidth > maxWidth || originHeight > maxHeight) {
              if (originWidth / originHeight > maxWidth / maxHeight) {
                // 更宽，按照宽度限定尺寸
                targetWidth = maxWidth;
                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
              } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
              }
            }
            // canvas对图片进行缩放
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            // 清除画布
            drawer.clearRect(0, 0, targetWidth, targetHeight);
            // 图片压缩
            drawer.drawImage(img, 0, 0, targetWidth, targetHeight);
            // canvas转为blob并上传
            canvas.toBlob(function (blob) {
              that.uploadimgs(img,blob);
            }, file.type || 'image/png');
          };
        }
      },
      uploadimgs(img,file){
        mui.showLoading("上传中...","div");
        var that = this;
        if(that.isapp){
          try{
            plus.zip.compressImage({
              src: img,
              dst: "_doc/chat/camera/" + img,
              quality: 20,
              overwrite: true
            },function (e) {
              var task=plus.uploader.createUpload(that.uploadUrl,
                {method:"POST",timeout: 60000},
                function(t,status){ //上传完成
                  var res = JSON.parse(t.responseText);
                  mui.hideLoading();
                  that.$previewRefresh();
                  that.$emit("getfile",that.imgname,that.imgs,that.files,res);
                }
              );
              task.addFile(e.target,{key:"file"});
              task.start();
              mui.later(function(){
                that.path='';
                that.imgs.splice(that.imgs.length-1,1);
                that.files.splice(that.files.length-1,1);
                task.abort();
                mui.hideLoading();
                mui.toast("上传失败请重试");
              },60000)
            },function (err) {
              that.path='';
              that.imgs.splice(that.imgs.length-1,1);
              that.files.splice(that.files.length-1,1);
              mui.hideLoading();
              mui.toast("图片压缩失败请重试");
            });
          }catch (e) {
            that.path='';
            that.imgs.splice(that.imgs.length-1,1);
            that.files.splice(that.files.length-1,1);
            mui.hideLoading();
            mui.toast("上传失败请重试");
          }
        }else{
          let formData = new FormData();
          formData.append('file',file,file.name);
          let config = {headers: {'Content-Type': 'multipart/form-data'}};
          that.$http.post(that.uploadUrl,formData,config).then(
            function(res){
              mui.hideLoading();
              that.$previewRefresh();
              that.$emit("getfile",that.imgname,that.imgs,that.files,res);
            }
          ).catch(function(e){
            var file = mui('#uploadfile')[0];
            file.value = '';
            that.path='';
            that.imgs.splice(that.imgs.length-1,1);
            that.files.splice(that.files.length-1,1);
            mui.hideLoading();
            mui.toast("上传失败请重试");
          });
        }
      }
    }
  }
</script>

<style scoped lang="less">
  .z-upload{
    overflow:hidden;
    .mask{
      position: relative;
      overflow:hidden;
      .upload-item{
        position: absolute;
        left: 0;
        top: 0;
        height:100%;
        width:100%;
      }
      input{
        opacity: 0;
      }
    }
    .z-badge{
      font-size: 12px;
      line-height: 1.4;
      position: absolute;
      top: -4px;
      left: 100%;
      margin-left: -14px;
      padding: 1px 5px;
      color: #fff;
      background: red;
    }
  }
</style>
